package com.dao.impl;

import com.dao.StudentsDao;
import com.entity.Students;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Repository
public class StudentsDaoImpl implements StudentsDao<Students> {

    @Resource
    private JdbcTemplate jdbcTemplate ;


    public void add(Students s) {
        System.out.println("新增学生:"+s);
        String sql = "INSERT INTO students VALUES(?, ?, ?, ?)";
        jdbcTemplate.update(sql, s.getSid(), s.getSname(), s.getGender(),s.getMajor());
    }

    public void query(String identify) {
        System.out.println("查询学生编号：" + identify);
        String sql = "SELECT * FROM students WHERE sid = ?";
        RowMapper<Students> rowMapper =new BeanPropertyRowMapper<>(Students.class);
        // 在将数据装入对象时需要调用set方法。
        Students s = jdbcTemplate.queryForObject(sql, rowMapper, identify);
        System.out.println(s);
    }

    public void delete(String identify) {
        System.out.println("删除学生编号：" + identify);
        String sql = "DELETE from students WHERE sid = ?";
        jdbcTemplate.update(sql, identify);
    }

    public void update(Students s) {
        System.out.println("修改学生:"+s);
        String sql = "UPDATE students SET sname = ?, gender=?,major=? WHERE sid = ?";
        jdbcTemplate.update(sql, s.getSname(),s.getGender(),s.getMajor(), s.getSid());
    }

    @Override
    public List<Students> queryAll() {
        String sql = "SELECT * from students";
        RowMapper<Students> rowMapper = new BeanPropertyRowMapper<>(Students.class);
        List<Students> userList = jdbcTemplate.query(sql, rowMapper);
        return userList;
    }

    @Override
    public void addBatch(List<Students> objs) {
        String sql = "INSERT INTO students VALUES(?, ?, ?, ?)";
        List<Object[]> batchArgs = new ArrayList<>();
        for(Students s: objs){
            batchArgs.add(new Object[] { s.getSid(), s.getSname(), s.getGender(),s.getMajor() });
        }

        jdbcTemplate.batchUpdate(sql, batchArgs);
    }
}

